#include "CinUserMap.h"

CinUserMap *CinUserMap::mInstance = NULL;

CinUserMap::CinUserMap()
{

}


CinUserMap::~CinUserMap()
{
    if (mInstance)
    {
        delete mInstance;
        mInstance = nullptr;
    }
    
}

CinUserMap* CinUserMap::GetInstance()
{
    if (!mInstance)
    {
        mInstance = new CinUserMap();
    }
    return mInstance;
}
    
void CinUserMap::addMap(int key, string user)
{
    mtx.lock(); 
    mUserMap.insert(std::map<int, string>::value_type(key, user));
    mtx.unlock();
}

void CinUserMap::addClient(int client, long time)
{
    mtx.lock(); 
    clients.insert(std::map<int, long>::value_type(client, time));
    mtx.unlock();
}

void CinUserMap::removeMap(int key)
{
   mtx.lock();
   std::map<int, string>::iterator findIt = mUserMap.find(key);
   if(findIt != mUserMap.end()){
        mUserMap.erase(findIt);
   }
   std::map<int, long>::iterator ct = clients.find(key);
   if(ct != clients.end()){
        clients.erase(ct);
   }
  
   mtx.unlock();
}

std::list<int> CinUserMap::getClients()
{   
    list<int> lists;
    std::map<int, long>::iterator  iter;  
    for(iter = clients.begin(); iter != clients.end(); iter++) 
    {
        lists.push_back(iter->first);
    }

    return lists;
}

void CinUserMap::updateClients(int key, long time)
{
    mtx.lock(); 
    clients[key] = time;
    mtx.unlock();
}
    
string CinUserMap::findUser(int key)
{
   string user ="";
   mtx.lock();
   user = mUserMap[key];
   mtx.unlock();
   return user;
}

//查找在线用户SOCKET 句柄
int CinUserMap::findUserByUid(string uid)
{   
    int key = -1;
    std::map<int, string>::iterator  iter;  
    for(iter = mUserMap.begin(); iter != mUserMap.end(); iter++) 
    {
        string val= iter->second;
        if(val.find(uid) != -1){
           key = iter->first;
           break;  
        }
    }
   return key;
}

/**
 *  查找SOCKET 在线时间值，用于保持在线
 * */
long CinUserMap::findFdTime(int fd)
{
    long rl = 0;
    std::map<int, long>::iterator ct = clients.find(fd);
    if(ct != clients.end())
    {
        rl = ct->second;
    } 

    return rl;
}